<?php

class storeActions extends sfActions {

    public function preExecute() {
        date_default_timezone_set(AppTools::TIMEZONE);
    }

    public function executeList(sfWebRequest $request) {
        $isActive = $request->getParameter('isActive', 1);
        $this->isActive = $isActive;

        $rows = StoreTable::getList($isActive);
        $this->rows = $rows;
    }

    public function executeUpdate(sfWebRequest $request) {
        $id = $request->getParameter('id');

        if ($id) {
            $store = StoreTable::retrieveByPK($id);
            if (!$store) {
                $this->getUser()->setFlash('warning', 'Салбар олдсонгүй');
                $this->redirect($request->getReferer());
            }
            $flash = 'Амжилттай заслаа';
        } else {
            $store = new Store();
            $flash = 'Амжилттай нэмлээ';
        }

        $form = new StoreForm($store);

        if ($request->isMethod('post')) {
            $form->bind($request->getParameter('store'));

            if ($form->isValid()) {
                $form->save();

                $this->getUser()->setFlash('success', $flash);
                $this->redirect('@store_list');
            }
        }

        $this->form = $form;
        $this->id = $id;
        $this->store = $store;
    }

    public function executeChangeState(sfWebRequest $request) {
        $store = StoreTable::retrieveByPk($request->getParameter('id'));
        if ($store) {
            if ($store->is_active == StoreTable::ACTIVE) {
                $store->setIsActive(StoreTable::PASSIVE);
                $this->getUser()->setFlash('success', 'Амжилттай устгалаа');
            } elseif ($store->is_active == StoreTable::PASSIVE) {
                $store->setIsActive(StoreTable::ACTIVE);
                $this->getUser()->setFlash('success', 'Амжилттай сэргээлээ');
            }
            $store->save();
        } else {
            $this->getUser()->setFlash('error', 'Салбар олдсонгүй!');
        }

        $this->redirect('@store_list');
    }

}
